﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace Sharp.Infrastructure.WebApiClient
{
    /// <summary>
    /// 服务配置
    /// </summary>
    public class WebApiServices
    {
        static readonly Dictionary<Type, HttpApiConfig> DicHttpApi = new Dictionary<Type, HttpApiConfig>();
        /// <summary>
        /// 添加Api
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Dictionary<Type, HttpApiConfig> AddContract<T>()
        {
            DicHttpApi.Add(typeof(T), null);
            return DicHttpApi;
        }

        internal static bool TryGetValue(Type key, out HttpApiConfig config)
        {
            return DicHttpApi.TryGetValue(key, out config);
        }

        public static void UpdateNullDic(HttpApiConfig config)
        {
            var temp = new List<Type>();
            foreach (var key in DicHttpApi.Keys)
            {
                var row = DicHttpApi[key];
                if (row == null)
                {
                    temp.Add(key);
                }
            }

            foreach (var key in temp)
            {
                DicHttpApi[key] = config;
            }
        }
    }
    /// <summary>
    /// 服务配置扩展方法
    /// </summary>
    public static class WebApiServicesEX
    {
        /// <summary>
        /// 添加Api
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hcs"></param>
        /// <returns></returns>
        public static Dictionary<Type, HttpApiConfig> AddContract<T>(this Dictionary<Type, HttpApiConfig> hcs)
        {
            WebApiServices.AddContract<T>();
            return hcs;
        }
        /// <summary>
        /// 配置
        /// </summary>
        /// <param name="hcs"></param>
        /// <param name="fc"></param>
        /// <returns></returns>
        public static Dictionary<Type, HttpApiConfig> ConfigureWebApiConfig(this Dictionary<Type, HttpApiConfig> hcs, Func<HttpApiConfig> fc)
        {
            var hac = fc.Invoke();

            WebApiServices.UpdateNullDic(hac);

            return hcs;
        }
    }
    /// <summary>
    /// 服务配置信息
    /// </summary>
    public class HttpApiConfig
    {
        /// <summary>
        /// 服务器地址
        /// </summary>
        public Uri HttpHost { get; set; }
        /// <summary>
        /// 过滤器
        /// </summary>
        public IActionFilter[] ActionFilters { get; set; }
    }
}
